package com.code2roc.jarmanage.servlet.project;

import com.code2roc.jarmanage.db.ProjectDB;
import com.code2roc.jarmanage.depoly.DepolyServiceFactory;
import com.code2roc.jarmanage.depoly.DepolyStatus;
import com.code2roc.jarmanage.model.ProjectDO;
import com.code2roc.jarmanage.model.ProjectModel;
import com.code2roc.jarmanage.model.Result;
import com.code2roc.jarmanage.util.CommonUtil;
import com.code2roc.jarmanage.util.ConvertUtil;
import com.code2roc.jarmanage.util.FileUtil;
import com.code2roc.jarmanage.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.ConvolveOp;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ListServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = Result.okResult();
        HashMap paramMap = CommonUtil.getParamMap(req);
        String projectName = ConvertUtil.convert2String(paramMap.get("projectName"));
        String sql = "1=1 and (DepolyType is null or DepolyType='')";
        if (!StringUtil.isEmpty(projectName)) {
            sql += " and projectName like '%" + projectName + "%'";
        }
        List<ProjectDO> entityList = ProjectDB.selectList(sql);
        List<ProjectModel> projectModelList = new ArrayList<>();
        for (ProjectDO entity:entityList) {
            ProjectModel model = new ProjectModel();
            model = ConvertUtil.convertSameStructObj(entity,model);
            String filePath = entity.getJarPackagePath()+ File.separator+entity.getServiceName()+".jar";
            if(new File(filePath).exists()){
                model.setProjectStatus(new DepolyServiceFactory().CreateDeployService().getStatus(model.getServiceName()));
            }else{
                model.setProjectStatus(DepolyStatus.UnUpload);
            }
            projectModelList.add(model);
        }
        result.add("obj", projectModelList);
        resp.getWriter().println(result.toString());
    }
}
